import { apiRequest, showNotification } from './utils.js';

// 文章管理模块
export class PostModule {
  constructor() {
    this.posts = [];
    this.categories = [];
    this.comments = [];
    this.postComments = [];
    this.newPost = {
      id: null,
      title: '',
      content: '',
      author: '',
      categoryId: null
    };
    this.editingPost = null;
    this.selectedPost = null;
  }

  // 加载文章列表
  async loadPosts() {
    try {
      this.posts = await apiRequest('/api/posts');
      return this.posts;
    } catch (error) {
      console.error('加载文章数据失败:', error);
      throw error;
    }
  }

  // 加载分类列表
  async loadCategories() {
    try {
      this.categories = await apiRequest('/api/categories');
      return this.categories;
    } catch (error) {
      console.error('加载分类数据失败:', error);
      throw error;
    }
  }

  // 加载所有评论
  async loadComments() {
    try {
      this.comments = await apiRequest('/api/comments');
      return this.comments;
    } catch (error) {
      console.error('加载评论数据失败:', error);
      throw error;
    }
  }

  // 加载特定文章的评论
  async loadPostComments(postId) {
    try {
      this.postComments = await apiRequest(`/api/posts/${postId}/comments`);
      return this.postComments;
    } catch (error) {
      console.error('加载文章评论失败:', error);
      throw error;
    }
  }

  // 创建或更新文章
  async savePost(postData) {
    try {
      let result;
      if (postData.id) {
        // 更新文章
        result = await apiRequest(`/api/posts/${postData.id}`, {
          method: 'PUT',
          body: JSON.stringify({
            title: postData.title,
            content: postData.content,
            categoryId: postData.categoryId
          })
        });
        // 更新本地列表
        const index = this.posts.findIndex(p => p.id === result.id);
        if (index !== -1) {
          this.posts[index] = result;
        }
        showNotification('文章更新成功', 'success');
      } else {
        // 创建新文章
        result = await apiRequest('/api/posts', {
          method: 'POST',
          body: JSON.stringify(postData)
        });
        this.posts.push(result);
        showNotification('文章发布成功', 'success');
      }
      return result;
    } catch (error) {
      console.error('保存文章失败:', error);
      throw error;
    }
  }

  // 删除文章
  async deletePost(postId) {
    try {
      await apiRequest(`/api/posts/${postId}`, {
        method: 'DELETE'
      });
      // 从本地列表中移除
      this.posts = this.posts.filter(p => p.id !== postId);
      showNotification('文章删除成功', 'success');
      return true;
    } catch (error) {
      console.error('删除文章失败:', error);
      throw error;
    }
  }

  // 设置编辑文章
  setEditingPost(post) {
    this.editingPost = post;
    if (post) {
      this.newPost = { ...post };
    } else {
      this.newPost = {
        id: null,
        title: '',
        content: '',
        author: '',
        categoryId: null
      };
    }
  }

  // 查看文章详情
  async viewPost(post) {
    this.selectedPost = post;
    await this.loadPostComments(post.id);
    return this.postComments;
  }

  // 获取分类名称
  getCategoryName(categoryId) {
    if (!categoryId) return '未分类';
    
    const category = this.categories.find(c => c.id === categoryId);
    return category ? category.name : '未知分类';
  }

  // 获取过滤后的文章列表
  getFilteredPosts(searchTerm = '') {
    if (!searchTerm) {
      return this.posts;
    }
    const search = searchTerm.toLowerCase();
    return this.posts.filter(post => 
      post.title.toLowerCase().includes(search) || 
      post.content.toLowerCase().includes(search) ||
      post.author.toLowerCase().includes(search)
    );
  }
}